// 全局变量
let albumsData = null;

// 当DOM加载完成后执行
document.addEventListener('DOMContentLoaded', async function() {
    // 加载相册数据
    albumsData = await DataLoader.loadAlbums();
    if (!albumsData) {
        showNotification('加载相册数据失败', 'error');
        return;
    }

    // 更新页面标题
    document.title = albumsData.pageTitle;

    // 更新页头信息
    const headerTitle = document.querySelector('.album-header h2');
    const headerDesc = document.querySelector('.album-header p');
    if (headerTitle && albumsData.headerInfo?.title) {
        headerTitle.textContent = albumsData.headerInfo.title;
    }
    if (headerDesc && albumsData.headerInfo?.description) {
        headerDesc.textContent = albumsData.headerInfo.description;
    }

    // 初始化相册分类
    initCategories();
    
    // 渲染相册
    renderAlbums();
    
    // 初始化相册功能
    initAlbum();
});

// 初始化相册分类
function initCategories() {
    if (!albumsData || !albumsData.categories) return;
    
    // 更新分类选项卡
    const categoryTabs = document.querySelector('.category-tabs');
    if (categoryTabs) {
        // 清空现有选项卡
        categoryTabs.innerHTML = '';
        
        // 添加新的选项卡
        albumsData.categories.forEach(category => {
            const tab = document.createElement('button');
            tab.className = 'category-tab' + (category.id === 'all' ? ' active' : '');
            tab.setAttribute('data-category', category.id);
            tab.textContent = category.name;
            categoryTabs.appendChild(tab);
        });
    }
    
    // 更新下拉菜单
    const categorySelect = document.getElementById('album-category');
    if (categorySelect) {
        // 清空现有选项
        categorySelect.innerHTML = '';
        
        // 添加新的选项
        albumsData.categories.forEach(category => {
            const option = document.createElement('option');
            option.value = category.id;
            option.textContent = category.name;
            categorySelect.appendChild(option);
        });
    }
}

// 渲染相册
function renderAlbums() {
    if (!albumsData || !albumsData.albums) return;
    
    const albumsGrid = document.querySelector('.albums-grid');
    if (!albumsGrid) return;
    
    // 清空现有相册
    albumsGrid.innerHTML = '';
    
    // 添加相册卡片
    albumsData.albums.forEach(album => {
        const albumCard = document.createElement('div');
        albumCard.className = 'album-card';
        albumCard.setAttribute('data-category', album.category);
        albumCard.setAttribute('data-id', album.id);
        
        // 格式化日期
        const formattedDate = DataLoader.formatDate(album.date);
        
        albumCard.innerHTML = `
            <div class="album-cover">
                <img src="${album.cover}" alt="${album.title}">
                <div class="album-count">${album.count}张</div>
            </div>
            <div class="album-info">
                <h3>${album.title}</h3>
                <p class="date">${formattedDate}</p>
            </div>
        `;
        
        // 添加点击事件
        albumCard.addEventListener('click', function() {
            openAlbumViewer(album);
        });
        
        albumsGrid.appendChild(albumCard);
    });
}

// 初始化相册功能
function initAlbum() {
    // 相册分类筛选
    initCategoryFilter();
    
    // 照片上传功能
    initPhotoUpload();
}

// 相册分类筛选
function initCategoryFilter() {
    const categoryTabs = document.querySelectorAll('.category-tab');
    const albumCards = document.querySelectorAll('.album-card');
    
    if (!categoryTabs.length || !albumCards.length) return;
    
    categoryTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除其他标签的active类
            categoryTabs.forEach(t => t.classList.remove('active'));
            
            // 添加当前标签的active类
            this.classList.add('active');
            
            const category = this.getAttribute('data-category');
            
            // 根据类别筛选相册
            albumCards.forEach(card => {
                if (category === 'all' || card.getAttribute('data-category') === category) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        });
    });
    
    // 下拉选择分类变化时
    const categorySelect = document.getElementById('album-category');
    if (categorySelect) {
        categorySelect.addEventListener('change', function() {
            const category = this.value;
            
            // 同步更新标签选中状态
            categoryTabs.forEach(tab => {
                if (tab.getAttribute('data-category') === category) {
                    tab.click();
                }
            });
        });
    }
}

// 照片上传功能
function initPhotoUpload() {
    const uploadBtn = document.getElementById('upload-btn');
    const fileInput = document.getElementById('file-upload');
    
    if (!uploadBtn || !fileInput) return;
    
    uploadBtn.addEventListener('click', function() {
        fileInput.click();
    });
    
    fileInput.addEventListener('change', function() {
        if (this.files.length > 0) {
            handleFileUpload(this.files);
        }
    });
}

// 处理文件上传
async function handleFileUpload(files) {
    if (!files || files.length === 0) return;
    
    try {
        // 显示上传中通知
        showNotification('正在上传照片，请稍候...', 'info');
        
        // 创建上传管理器
        const uploadManager = new UploadManager();
        
        // 上传第一张照片作为封面
        const coverUploadResult = await uploadManager.uploadImage(files[0], 'albums');
        if (!coverUploadResult.success) {
            throw new Error('上传封面照片失败');
        }
        
        // 准备相册数据
        const today = new Date();
        const albumData = {
            title: `新相册-${today.getFullYear()}${today.getMonth() + 1}${today.getDate()}`,
            date: today.toISOString().split('T')[0],
            category: 'daily', // 默认为日常类别
            cover: coverUploadResult.filePath,
            count: files.length,
            photos: []
        };
        
        // 如果上传了多张照片，则上传剩余照片
        for (let i = 1; i < files.length; i++) {
            try {
                const photoUploadResult = await uploadManager.uploadImage(files[i], 'albums');
                if (photoUploadResult.success) {
                    albumData.photos.push({
                        src: photoUploadResult.filePath,
                        title: `照片${i}`,
                        description: `${albumData.title}的照片${i}`
                    });
                }
            } catch (photoError) {
                console.error('上传照片失败:', photoError);
                // 继续上传其他照片
            }
        }
        
        // 保存相册数据
        const result = await uploadManager.addAlbum(albumData);
        
        if (result.success) {
            showNotification(`成功上传${files.length}张照片，并创建了新相册！`, 'success');
            // 刷新页面显示新相册
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            throw new Error('保存相册数据失败');
        }
    } catch (error) {
        console.error('处理文件上传错误:', error);
        showNotification(`上传失败: ${error.message}`, 'error');
    }
}

// 打开相册查看器
function openAlbumViewer(album) {
    // 获取需要显示的相册
    if (!album) return;
    
    // 清除现有模态框内容或创建新的
    let viewerModal = document.getElementById('album-viewer-modal');
    if (!viewerModal) {
        viewerModal = document.createElement('div');
        viewerModal.id = 'album-viewer-modal';
        viewerModal.className = 'modal fade';
        viewerModal.setAttribute('tabindex', '-1');
        viewerModal.setAttribute('aria-labelledby', 'albumViewerModalLabel');
        viewerModal.setAttribute('aria-hidden', 'true');
        document.body.appendChild(viewerModal);
    }
    
    // 格式化日期
    const formattedDate = DataLoader.formatDate(album.date);
    
    // 构建相册照片列表
    let photosHTML = '';
    if (album.photos && album.photos.length > 0) {
        album.photos.forEach(photo => {
            photosHTML += `
                <div class="album-photo">
                    <img src="${photo.src}" alt="${photo.title}" class="img-fluid">
                    <div class="photo-info">
                        <h5>${photo.title}</h5>
                        <p>${photo.description}</p>
                    </div>
                </div>
            `;
        });
    } else {
        photosHTML = '<p class="text-center">该相册暂无照片</p>';
    }
    
    // 设置模态框内容
    viewerModal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="albumViewerModalLabel">${album.title}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <div class="album-info mb-3">
                        <p class="text-muted">${formattedDate} · ${album.count}张照片</p>
                    </div>
                    <div class="album-photos">
                        ${photosHTML}
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    `;
    
    // 显示模态框
    const modal = new bootstrap.Modal(viewerModal);
    modal.show();
}

// 显示通知消息
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <p>${message}</p>
            <button class="close-notification">&times;</button>
        </div>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.classList.add('show');
    }, 10);
    
    // 自动关闭
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
    
    // 手动关闭
    notification.querySelector('.close-notification').addEventListener('click', () => {
        notification.classList.remove('show');
        setTimeout(() => {
            notification.remove();
        }, 300);
    });
}

// 工具函数：格式化日期
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}年${month}月${day}日`;
} 